<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>写字板</title>
</head>

<body>
    <canvas id="canvas"></canvas>
    <button onclick="save()">保存签名</button>
    <script>
        let isDown = false
        let canvas = document.getElementById("canvas");
        let ctx = canvas.getContext("2d");
        canvas.width = 600;
        canvas.height = 400;
        canvas.style.border = "1px solid black";
        canvas.addEventListener("mousedown", function (event) {
            isDown = true;
            ctx.beginPath();
            ctx.moveTo(event.clientX, event.clientY);
        })
        canvas.addEventListener("mousemove", function (event) {
            if(isDown) {
                ctx.lineTo(event.clientX, event.clientY);
                ctx.stroke();
            }
        })
        canvas.addEventListener("mouseup", function (event) {
            isDown = false
            ctx.closePath();
        })
        function save() {
            let dataURL = canvas.toDataURL("image/png");
            let a = document.createElement("a");
            a.href = dataURL;
            a.download = "signature.png";
            a.click();
            clear();
        }
        function clear() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        }
    </script>
</body>

</html>